package ink.onei.production.service.impl;

import ink.onei.production.entity.Customer;
import ink.onei.production.entity.Goods;
import ink.onei.production.entity.Order;
import ink.onei.production.exception.OperateException;
import ink.onei.production.mapper.IOrderMapper;
import ink.onei.production.service.ICustomerService;
import ink.onei.production.service.IGoodsService;
import ink.onei.production.service.IOrderService;
import ink.onei.production.vo.OrderDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: nekotako
 * @Description: TODO
 * @Date: 26/12/2023 20:51 Tuesday
 */

@Service
public class OrderService implements IOrderService {

    @Autowired
    private IOrderMapper orderMapper;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IGoodsService goodsService;

    @Override
    public List<OrderDetailVO> getOrderList(OrderDetailVO orderDetail, Integer id, String customerName, String goodsName, String priceUnit, String status) {
        return orderMapper.getOrderList(orderDetail, id, customerName, goodsName, priceUnit, status);
    }

    @Override
    public Integer add(OrderDetailVO orderDetail) throws OperateException {
//        先查询客户和商品是否存在
//        存在直接查询出客户和商品ID并添加订单
//        不存在则抛出不存在异常
        Customer customer = customerService.getCustomer(orderDetail.getCustomer());
        Goods goods = goodsService.getGoods(orderDetail.getGoods());

        if (customer == null) {
            throw new OperateException("客户不存在");
        }
        if (goods == null) {
            throw new OperateException("商品不存在");
        }

        Order order = orderDetail.getOrder();
        order.setCustomerId(customer.getId());
        order.setGoodsId(goods.getId());
        return orderMapper.insert(order);
    }

    public Integer add2(OrderDetailVO orderDetail) {
//        先查询客户和商品是否存在
//        存在直接查询出客户和商品ID并添加订单
//        不存在则先进行添加 再添加订单
        Customer customer = customerService.getCustomer(orderDetail.getCustomer());
        Integer customerId = customer == null ? customerService.add(orderDetail.getCustomer()) : customer.getId();

        Goods goods = goodsService.getGoods(orderDetail.getGoods());
        Integer goodsId = goods == null ? goodsService.add(orderDetail.getGoods()) : goods.getId();

        Order order = orderDetail.getOrder();
        order.setCustomerId(customerId);
        order.setGoodsId(goodsId);
        return orderMapper.insert(order);
    }

    @Override
    public Integer modify(Order order) {
        return orderMapper.update(order);
    }

    @Override
    public Integer delete(Order order) {
        return orderMapper.delete(order);
    }

    @Override
    public Integer deleteBatch(List<Order> orderList){
        return orderMapper.deleteBatch(orderList);
    }
}
